<template>
  <a-spin :spinning="confirmLoading">
    <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol">
      <a-row>
        <template v-if="!formData.id">
          <a-col :span="24">
            <a-form-item label="服务公司" v-bind="validateInfos.serviceCompanyId">
              <j-dict-select-tag v-model:value="formData.serviceCompanyId"
                                 dictCode="caishui_middle_company,company_name,company_id"
                                 placeholder="请选择服务公司" :disabled="disabled"/>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="一档税率" v-bind="validateInfos.taxRate">
              <a-input v-model:value="formData.taxRate" placeholder="请输入一档税率" style="width: 100%" :disabled="disabled" addon-after=" % "/>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="二档税率" v-bind="validateInfos.taxRateTwo">
              <a-input v-model:value="formData.taxRateTwo" placeholder="请输入二档税率" style="width: 100%" :disabled="disabled" addon-after=" % "/>
            </a-form-item>
          </a-col>
        </template>

        <template v-if="formData.id">
          <a-col :span="24">
            <a-form-item label="当前一档税率" v-bind="validateInfos.curTaxRate">
              <span>{{(parseFloat(formData.curTaxRate)*100).toFixed(4)}}</span>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="设置一档税率" v-bind="validateInfos.taxRate">
              <a-input v-model:value="formData.taxRate" placeholder="请输入一档税率" style="width: 100%" :disabled="disabled" addon-after=" % "/>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="当前二档税率" v-bind="validateInfos.curTaxRateTwo">
              <span>{{(parseFloat(formData.curTaxRateTwo)*100).toFixed(4)}}</span>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="设置二档税率" v-bind="validateInfos.taxRateTwo">
              <a-input v-model:value="formData.taxRateTwo" placeholder="请输入二档税率" style="width: 100%" :disabled="disabled" addon-after=" % "/>
            </a-form-item>
          </a-col>
        </template>
<!--        <a-col :span="24">
          <a-form-item label="税率类型" v-bind="validateInfos.taxRateType">
            <j-dict-select-tag type='radio' v-model:value="formData.taxRateType" dictCode="caishui_tax_rate_type" placeholder="请选择税率类型" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="支付宝PID" v-bind="validateInfos.zfbPid">
            <a-input v-model:value="formData.zfbPid" placeholder="请输入支付宝PID" :disabled="disabled"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="代发类型" v-bind="validateInfos.issuingType">
	          <j-dict-select-tag v-model:value="formData.issuingType" dictCode="caishui_issuing_type" placeholder="请选择代发类型" :disabled="disabled"/>
          </a-form-item>
        </a-col>-->
      </a-row>
    </a-form>
  </a-spin>
</template>

<script lang="ts" setup>
import { computed, defineExpose, defineProps, nextTick, reactive, ref } from "vue";
import { useMessage } from "/@/hooks/web/useMessage";
import JDictSelectTag from "/@/components/Form/src/jeecg/components/JDictSelectTag.vue";
import { getValueType } from "/@/utils";
import { saveOrUpdate } from '../CaishuiBusinessBank.api';
import { Form } from "ant-design-vue";

const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: ()=>{} },
    formBpm: { type: Boolean, default: true }
  });
  const formRef = ref();
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    id: '',
    businessId: '',
    serviceCompanyId: '',
    accountName: '',
    taxRate: '',
    taxRateTwo: '',
    curTaxRate: '',
    curTaxRateTwo: '',
    taxRateType: undefined,
    zfbPid: '',
    issuingType: undefined,
  });
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  //表单验证
  const validatorRules = {
    serviceCompanyId: [{ required: true, message: '请选择服务公司!'},],
    taxRate: [
      { required: true, message: '请输入一档税率!'},
      { validator: taxRateNumValidate }
    ],
    taxRateTwo: [
      { required: true, message: '请输入二档税率!'},
      { validator: taxRateNumValidate }
    ],
    // taxRateType: [{ required: true, message: '请选择税率类型!'},],
    // zfbPid: [{ required: true, message: '请输入支付宝PID!'},],
    // issuingType: [{ required: true, message: '请选择代发类型!'},],
  };
  const { resetFields, validate, validateInfos, clearValidate } = useForm(formData, validatorRules, { immediate: true });

   // 表单禁用
   const disabled = computed(()=>{
      let bool = false;
      if(props.formBpm === true){
        if(props.formData.disabled === false){
          bool = false;
        }else{
          bool =  true;
        }
      }
      bool = props.formDisabled;
      if(bool){
        //清除表单验证
        clearValidate();
      }
      return bool;
   });


  /**
   * 新增
   */
  function add(record) {
    edit(record);
  }

  /**
   * 编辑
   */
  function edit(record) {
    console.log("--record---:",record)
    nextTick(() => {
      resetFields();
      //设置税率
      formData.curTaxRate = record.taxRate;
      formData.curTaxRateTwo = record.taxRateTwo;
      //赋值
      Object.assign(formData, record);
      formData.taxRate = '';
      formData.taxRateTwo = '';
    });
  }

  function taxRateNumValidate(rule, value, callback){
    if(value){
      let reg = /^(([1-9][0-9]*)|([0]\.\d{0,4}|[1-9][0-9]*\.\d{0,5}))$/;
      if(!reg.test(value)){
        callback("税率必须为数字!");
      }else if(parseFloat(value) <= 0 || parseFloat(value) > 50){
        callback("税率必须大于0且小于等于50!");
      }else {
        callback();
      }
    }else {
      callback();
    }
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    // 触发表单验证
    await validate();
    if(!formData.businessId){
      createMessage.error("参数错误");
      return;
    }
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //数据格式化
    let model = formData;
    if (model.id) {//编辑
       isUpdate.value = true;
       model.updateBy = "";
       model.updateTime = "";
    }else {//新增
       model.createBy = "";
       model.createTime = "";
       model.sysOrgCode = "";
       model.updateBy = "";
       model.updateTime = "";
    }
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    console.log('表单提交数据', model)
    await saveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }

  defineExpose({
    add,
    edit,
    submitForm,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    overflow-y: auto;
    padding: 24px 24px 24px 24px;
  }
</style>
